<?php
if (!defined('BASEPATH'))
	exit('No direct script access allowed');

define('RUNNING_COUNT', 50000);

class Chinese extends CI_Controller {

	/*
	 * 操作页面
	 */
	public function index() {

		$this -> load -> dbutil();

		$dbs = $this -> dbutil -> list_databases();

		$data['from_db'] = $data['to_db'] = $dbs;

		$this -> load -> view('chinese', $data);

	}

	/*
	 * 执行页面
	 */
	public function run() {

		/*
		 * 状态初始化
		 */
		extract($_POST);

		if (empty($from_db) || empty($to_db)) {

			redirect('/', 'refresh');
		}

		$data = array('from_db' => array($from_db), 'to_db' => array($to_db), 'replace' => $replace, 'rule' => $rule);

		$this -> load -> helper('exdb');

		if (empty($status)) {

			/*
			 * 初始化汉化状态
			 */
			$status['tables'] = exdb_list_tables($from_db);
			$status['log'] = $from_db . '_' . date('m-d.H.i.s', time()) . '_' . bindec(rand(0, 255));

		} else {

			/*
			 * 还原汉化状态
			 */
			$status = json_decode($status, TRUE);
		}

		/*
		 * 执行汉化
		 */
		if (empty($status['table'])) {

			$this -> next_table($from_db, $to_db, $status);
		}

		/*
		 * 执行汉化方法
		 */
		if (empty($status['table'])) {

			$data['message'] = "汉化执行完毕";

		} else {

			/*
			 * 展开状态数据
			 */
			extract($status);

			$index = intval($index);

			$message = $index . '=>[' . $table . ']:';
			$message .= implode(',', $from_keys) . '=>' . implode(',', $to_keys);
			$message .= '{' . implode(',', $from_chars) . '=>' . implode(',', $to_chars) . '}';
			$data['message'] = $message;

			/*
			 * 日志
			 */
			$logs = array();
			$index = $this -> convert_to_chinese($from_dbtable, $to_dbtable, $from_keys, $to_keys, $from_chars, $to_chars, $index, $logs);

			/*
			 * 自动刷新
			 */
			if (!isset($_GET['stop'])) {
				$data['refresh'] = TRUE;
			}

			/*
			 * 纪录已经执行指针
			 */
			if ($index <= 0) {

				$status['table'] = null;
			} else {

				$status['index'] = $index;
			}

			/*
			 * 纪录日志
			 */
			$this -> load -> helper('file');
			write_file('./logs/' . $status['log'] . '.sql', reset($logs), 'a+');
		}

		/*
		 * 显示视图
		 */
		$data['status'] = json_encode($status);
		$this -> load -> view('chinese', $data);
	}

	/*
	 * 获取下一个表状态
	 */
	private function next_table($from_db, $to_db, &$status) {

		$tables = &$status['tables'];

		foreach ($tables as $key => $table) {

			unset($tables[$key]);

			$from_dbtable = exdb_dbtable($from_db, $table);
			$to_dbtable = exdb_dbtable($to_db, $table);

			if ($this -> db_table_status($from_dbtable, 'from', $status) && $this -> db_table_status($to_dbtable, 'to', $status) && $this -> db_key_status($from_dbtable, $to_dbtable, $status) && $this -> db_char_status($status)) {

				$status['index'] = 0;
				$status['table'] = $table;
				$status['from_dbtable'] = $from_dbtable;
				$status['to_dbtable'] = $to_dbtable;

				break;
			}
		}
	}

	/*
	 * 获取索引|文字字段
	 */
	private function db_table_status($dbtable, $prefix, &$status) {

		exdb_debug(FALSE);

		$fields = exdb_list_fields($dbtable);

		exdb_debug();

		if ($fields) {

			$keys = exdb_key_arrays($fields);

			if ($keys) {

				$chars = exdb_char_arrays($fields);

				if ($chars) {

					$status[$prefix . '_keys'] = $keys;
					$status[$prefix . '_chars'] = $chars;

					return TRUE;
				}
			}
		}

		return FALSE;
	}

	/*
	 * 索引字段匹配
	 */
	private function db_key_status($from_table, $to_table, &$status) {

		$similar_status = exdb_similar_fields($status['from_keys'], $status['to_keys'], $from_table, $to_table);

		$from_fields = $similar_status['from_fields'];

		if (count($from_fields) > 0) {

			$to_fields = $similar_status['to_fields'];
			if (count($similar_status['to_others']) <= 0 || exdb_fields_iskey($to_fields, $to_table)) {

				$status['from_keys'] = $from_fields;
				$status['to_keys'] = $to_fields;

				return TRUE;
			}
		}

		return FALSE;

	}

	/*
	 * 文字字段匹配
	 */
	private function db_char_status(&$status) {

		$similar_status = exdb_similar_fields($status['from_chars'], $status['to_chars']);

		$from_fields = $similar_status['from_fields'];

		if (count($from_fields) > 0) {

			$status['from_chars'] = $from_fields;
			$status['to_chars'] = $similar_status['to_fields'];

			return TRUE;
		}

		return FALSE;
	}

	/*
	 * 执行汉化方法
	 */
	private function convert_to_chinese($from_dbtable, $to_dbtable, $from_keys, $to_keys, $from_chars, $to_chars, $index, &$logs) {

		$log = '';
		$logs = array(&$log);

		$to_db_ = exdb_name($_POST['to_db']) . '.';

		$replace = intval($_POST['replace']);
		$rule = intval($_POST['rule']);

		$query = exdb_keys_chars_query($from_dbtable, $to_dbtable, $from_keys, $to_keys, $from_chars, $to_chars, $index . ',' . RUNNING_COUNT);

		/*
		 * 迭代汉化
		 */
		while ($row = $query -> _fetch_assoc()) {

			/*
			 * 判断目标纪录是否存在
			 */
			if ($row['tid'] == NULL && $replace == 0) {
				continue;
			}

			/*
			 * 获取更新数据
			 */
			$updates = array();
			foreach ($from_chars as $key => $from_char) {

				$from = $row['from_' . $key];

				if (preg_match("/[\x{4e00}-\x{9fa5}]+/u", $from)) {

					$to = $row['to_' . $key];

					$doto = FALSE;
					if (preg_match("/[\x{4e00}-\x{9fa5}]+/u", $to)) {

						switch($rule) {

							case(0) :
								$doto = TRUE;
								break;

							case(2) :
								$doto = strlen($from) > strlen($to);
								break;

							case(3) :
								$doto = strlen($from) < strlen($to);
								break;
						}

					} else {

						$doto = TRUE;
					}

					if ($doto == TRUE) {

						/*汉化debug
						 if(!isset($_GET['stop'])) {
						 $_GET['stop'] = TRUE;
						 echo $from,'<br/>',$to;
						 }
						 //*/

						$updates[$to_chars[$key]] = $from;
					}
				}
			}

			/*
			 * 执行更新
			 */
			if (count($updates) > 0) {

				if ($row['tid'] == NULL) {

					/*
					 * 替换字段 
					 */
					foreach ($to_keys as $key => $to_key) {

						$updates[$to_key] = $row['key_' . $key];

					}

					$updateSql = $this -> db -> insert_string($to_dbtable, $updates);

					$index = 1;
					$updateSql = str_ireplace('INSERT INTO', 'REPLACE INTO', $updateSql, $index);

				} else {

					/*
					 * 更新条件
					 */
					$condition = array();
					foreach ($to_keys as $key => $to_key) {

						$condition[$to_key] = $row['key_' . $key];
					}

					$updateSql = $this -> db -> update_string($to_dbtable, $updates, $condition);
				}

				if ($this -> db -> simple_query($updateSql) > 0) {
						
					$index = 1;
					$log .= str_replace($to_db_, '', $updateSql, $index) . ";\r\n";	
				}
			}
		}

		/*
		 * 索引递增
		 */
		if ($query -> num_rows() < RUNNING_COUNT) {

			$index = -1;
		} else {

			$index += RUNNING_COUNT;
		}

		return $index;
	}

}
